#include <iostream>
#include <unistd.h>
#include <pthread.h>

// pthread2中已经验证了线程之间共享函数了
// pthread3验证线程之间共享栈,共享全局变量和线程的局部存储

int gval1 = 10;
__thread int gval2 = 100;
int *gp = nullptr;
int count = 0; // 模拟计时器,分开验证三种情况

std::string ToHex(pthread_t pid)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", pid);
    return buffer;
}

// 共享全局变量的验证
void *rutine1(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (count < 7)
    {
        std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "gval1:" << gval1 << std::endl;
        count += 1;
        sleep(1);
    }
    return nullptr;
}
void *rutine2(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (count < 7)
    {
        gval1 += 1;
        std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "gval1:" << gval1 << std::endl;
        sleep(1);
    }
    return nullptr;
}

// 线程的局部存储
void *rutine3(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (count >= 7 && count < 14)
    {
        std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "gval2:" << gval2 << std::endl;
        count++;
        sleep(1);
    }
    return nullptr;
}
void *rutine4(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (count >= 7 && count < 14)
    {
        gval2 += 10;
        std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "gval2:" << gval2 << std::endl;
        sleep(1);
    }
    return nullptr;
}

// 验证共享栈区
void *rutine5(void *args)
{
    std::string name = static_cast<const char *>(args);
    int rutine5a = 1;
    std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "rutine5a:" << rutine5a << std::endl;
    sleep(4);
    gp = &rutine5a;
    sleep(2);
    std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "rutine5a:" << rutine5a << std::endl;

    return nullptr;
}
void *rutine6(void *args)
{
    std::string name = static_cast<const char *>(args);
    sleep(5);
    *gp=10000;
    std::cout << "我是子线程:" << ToHex(pthread_self()) << name << "我修改rutine5a为10000" << std::endl;

    return nullptr;
}

int main()
{
    // 共享全局变量
    pthread_t th1, th2, th3, th4,th5,th6;
    pthread_create(&th1, nullptr, rutine1, (void *)"pthread-1");
    pthread_create(&th2, nullptr, rutine2, (void *)"pthread-2");

    sleep(8);
    pthread_create(&th3, nullptr, rutine3, (void *)"pthread-3");
    pthread_create(&th4, nullptr, rutine4, (void *)"pthread-4");

    // 等待子线程
    pthread_join(th1, nullptr);
    pthread_join(th2, nullptr);
    pthread_join(th3, nullptr);
    pthread_join(th4, nullptr);

    sleep(10);
    pthread_create(&th5, nullptr, rutine5, (void *)"pthread-5");
    pthread_create(&th6, nullptr, rutine6, (void *)"pthread-6");
    pthread_join(th5, nullptr);
    pthread_join(th6, nullptr);
    return 0;
}